<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/layouts/taglib.jsp" %>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>文章分类</title>
	<%@include file="/WEB-INF/layouts/edit-header.jsp"%>
	<link rel="stylesheet" href="${staticPath}/admin/lib/nestable/jquery.nestable.css"/>
	<link rel="stylesheet" href="${staticPath}/admin/lib/Font-Awesome/css/font-awesome.min.css"/>
	<style type="text/css">
		body {
			padding: 20px;
		}

		.tpanel .panel-title {
			border-bottom: 1px solid #E7EAEC;
		}

		.dd-handle {
			background: #FFF;
		}

		.dd-handle .op {
			position: absolute;
			right: 10px;
			top: 0px;
			bottom: 0px;
			line-height: 32px;
		}

		.dd-handle .op div {
			display: inline-block;
			margin-left: 5px;
		}

		.dd-handle .op div.modify {
			color: #19AA8D;
		}

		.dd-handle .op div.delete {
			color: #F57575;
		}

		.tpanel .panel-content {
			padding-top: 10px;
		}
	</style>
	<script src="${staticPath}/admin/tcsf/wg_listToTree1.1.js"></script>
	<script type="text/javascript" src="${staticPath}/admin/lib/nestable/jquery.nestable.js"></script>
	<script type="text/javascript" src="${staticPath}/admin/tcsf/tcsf.nestable.js"></script>

</head>
<body>

<div class="container-fluid">
	<div class="row">
		<div class="col-sm-3">
			<div class="tpanel">
				<div class="panel-title">
					<h5>类别排序</h5>
				</div>
				<div class="panel-content">
					<div class="container-fluid">
						<div class="dd">

						</div>
						<div class="row" style="padding-top:15px;padding-bottom:15px;">
							<div class="col-sm-6">
								<button type="button" class="btn btn-default" onclick="saveSort()" style="padding-left:12px;padding-right:12px;">保存顺序</button>
							</div>
							<div class="col-sm-6">
								<button type="button" class="btn btn-primary" onclick="createMenu()" style="padding-left:12px;padding-right:12px;">创建类别</button>
							</div>
						</div>
					</div>
				</div>
			</div>

		</div>
		<div class="col-sm-9">

			<div class="tpanel">
				<div class="panel-title">
					<h5 id="menuFormTitle">创建类别</h5>
				</div>
				<div class="panel-content">
					<div class="container-fluid">
						<form id="menuForm" class="form-horizontal">
							<input id="id" name="id" type="hidden"/>
							<div class="form-group form-group-first">
								<label for="catalogName" class="col-sm-2 control-label">类别名称</label>
								<div class="col-sm-10">
									<input type="text" class="form-control" name="catalogName" id="catalogName" placeholder="类别名称"
										   required maxlength="20"/>
								</div>
							</div>
							<div class="form-group">
								<div class="col-sm-2"></div>
								<div class="col-sm-10">
									<button type="submit" class="btn btn-primary">
										保&nbsp;&nbsp;&nbsp;&nbsp;存
									</button>
								</div>
							</div>

						</form>
					</div>
				</div>
			</div>

		</div>
	</div>
</div>

<script type="text/javascript">
    changeTitle('文章分类');
    jQuery(function () {
        loadMenuTree();
        $('.dd').nestable({maxDepth: 3});
    });

    function createMenu() {
        $('#menuForm')[0].reset();
        $('#menuFormTitle').text('创建类别');
        $('#id').val('');
        $('#description').text('');
    }

    function modifyMenu(id, e) {
        $.getJSON('${ctx}/admin/cms/article-catalog/get?id=' + id, function (resp) {
            if (resp.code == 'OK') {
                $('#menuFormTitle').text('编辑类别');
                $('#id').val(resp.body.id);
                validator.resetForm();
                $('#catalogName').val(resp.body.catalogName);
            } else {
                topLayer.msg('获取类别信息失败:' + resp.message, {icon: 2});
            }
        });
        stopBubble(e);
    }

    function loadMenuTree() {
        generateNestableTree('${ctx}/admin/cms/article-catalog/list', '.dd', 'modifyMenu', 'deleteMenu');
    }

    function saveSort() {
        var json = $('.dd').nestable('serialize');
        topLayer.load();
        $.ajax({
            type: "POST",
            url: '${ctx}/admin/cms/article-catalog/save-sort',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(json),
            dataType: "json",
            success: function (resp) {
                topLayer.closeAll('loading');
                if (resp.code == 'OK') {
                    topLayer.msg('保存成功', {icon: 1});
                    createMenu();
                    loadMenuTree();
                } else {
                    topLayer.msg(resp.message, {icon: 2});
                }
            },
            error: function (message) {
                topLayer.closeAll('loading');
                topLayer.msg(message, {icon: 2});
            }
        });
    }

    function deleteMenu(id, e) {
        topBootbox.prompt({
            title: "请输入您的管理密码以确定删除此系统菜单",
            onEscape: true,
            backdrop: true,
            animate: true,
            buttons: {
                confirm: {
                    label: '删除',
                    className: 'btn-danger'
                },
                cancel: {
                    label: '取消',
                    className: ''
                }
            },
            inputType: 'password',
            callback: function (result) {
                if (result) {
                    $.post('${ctx}/admin/cms/article-catalog/careful-delete', {id: id, password: result}, function (resp) {
                        if (resp.code == 'OK') {
                            topLayer.msg('删除成功', {icon: 1});
                            loadMenuTree();
                            createMenu();
                        } else {
                            topLayer.msg('删除失败:' + resp.message, {icon: 2});
                        }
                    }, 'json');
                }
            }
        });

        stopBubble(e);
    }


    var validator;
    $(function () {
        validator = $('#menuForm').validate({
            focusCleanup: true,
            focusInvalid: false,
            errorClass: "unchecked",
            validClass: "checked",
            errorElement: "span",
            submitHandler: function (form) {
                var url = "${ctx}/admin/cms/article-catalog/create";
                if ($('#id').val().length > 0) {
                    url = "${ctx}/admin/cms/article-catalog/update";
                }
                console.log(url);
                $(form).ajaxSubmit({
                    type: "post",
                    url: url,
                    beforeSubmit: function () {
                        topLayer.load();
                    },
                    success: function (r) {
                        var resp = $.parseJSON(r);
                        window.parent.layer.closeAll('loading');
                        if (resp.code == 'OK') {
                            topLayer.msg('保存成功', {icon: 1});
                            createMenu();
                            loadMenuTree();
                        } else {
                            topLayer.msg(resp.message, {icon: 2});
                        }
                    }
                });
                return false;
            },
            errorPlacement: function (error, element) {
                var s = element.parent().find("span[htmlFor='" + element.attr("id") + "']");
                if (s != null) {
                    s.remove();
                }
                error.appendTo(element.parent());
            },
            success: function (label) {
                label.removeClass("unchecked").addClass("checked");
            }
        });
    });

    function generateNestableTree(url,target,modifyFun,deleteFun) {
        $.getJSON(url,function(result) {
            if(result.code == 'OK') {
                fillData(result.body);
            }
        });

        function fillData(data) {
            var param = {
                list:data,
                inParams:{
                    pid:"parentId",
                    rootId : null,
                    id:'id'
                },
                outParams:{
                    children:"children",
                    pid:"pid",
                    id:'id'
                },
                sort:{
                    orderBy:["sort"],
                    sort:"asc"
                }
            };
            var tree = wg_listToTree(param);
            var html = '<ol class="dd-list">';
            for(var index in tree) {
                html += generate(tree[index],true);
            }
            html += '</ol>';
            $(target).html(html);
            $(target).nestable('collapseAll');
        }
        function generate(item,hasIcon) {
            var html = '';
            if(item) {
                var hasChildren = item.children && item.children.length;
                html += '<li class="dd-item" data-id="' + item.id + '">';
                if(hasChildren) {
                    html += '<button data-action="collapse" type="button">Collapse</button>';
                    html += '<button data-action="expand" type="button" style="display: none;">Expand</button>';
                }
                html += '<div class="dd-handle">';
                html += '<span>' + item.catalogName + '</span>';
                html += '<div class="op">';
                html += '<div class="modify" title="编辑" onmousedown="' + modifyFun + '(' + item.id + ',event)">'
                    + '<i class="iconfont icon-iconfontcolor32"></i></div>';
                html += '<div class="delete" title="删除" onmousedown="' + deleteFun + '(' + item.id + ',event)">'
                    + '<i class="iconfont icon-shanchu"></i></div>';
                html += '</div>';
                html += '</div>';
                /*if(hasIcon) {
                     html += '<i class="iconfont ' + item.iconCls + '"></i>';
                 }*/
                /*html += '<span>' + item.name + '</span>';*/
                /*if(hasChildren) html += '<i class="arrow iconfont icon-lunbozuofangun"></i>';
                html += '</a>';*/
                if(hasChildren) {
                    html += '<ol class="dd-list">';
                    for(var index in item.children) {
                        var child = item.children[index];
                        html += generate(child,false);
                    }
                    html += '</ol>';
                }
                html += '</li>';
            }
            return html;
        }
    }

</script>
</body>
</html>
